<?php

class Admin_uploadController {

    public function fileAction() {

        $file_dir = '/www/wwwroot/wxc/wxch5/dist/Images/admin/images/'.date('Ymd');
        $url = "http://wxch5.chei.org/Images/admin/images/".date('Ymd');
        $targetDir = APP_ROOT.'/upload_tmp';
        $uploadDir = $file_dir;

        $cleanupTargetDir = true;
        $maxFileAge = 5 * 3600;

        if (!file_exists($targetDir)) {
            File::makeDir($targetDir);
        }

        if (!file_exists($uploadDir)) {
            File::makeDir($uploadDir);
        }

        if (isset($_REQUEST["name"])) {
            $fileExt = strtolower(substr(strrchr($_REQUEST["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif(in_array($fileExt, array('php'))) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_REQUEST["name"]).'.'.$fileExt;
            }


        } elseif (!empty($_FILES)) {
            $fileExt = strtolower(substr(strrchr($_FILES["file"]["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif (strpos($_FILES["file"]['type'], 'php')) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_FILES["file"]["name"]).'.'.$fileExt;
            }
        } else {
            $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        
//        //oss上传
//        
//        $ossClient = new OssClient(Configure::get('oss.access_key'), Configure::get('oss.access_secret'), Configure::get('oss.endpoint'), false);
//        try {
//            $ossClient->multiuploadFile(Configure::get('oss.bucket'), $file_dir.'/'.$fileName, $uploadPath, array());
//        } catch (OssException $e) {
//            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream.'.$e->getMessage().'"}, "id" : "id"}');
//        }
        $data = array(
            'jsonrpc' => '2.0',
            'result' => null,
            'id' => 'id',
            'error' => array(
                'code' => 0
            ),
            'url' => $url.'/'.$fileName,
            'image' => in_array($fileExt, array('jpg','png','gif','jpeg'))?($url.'/'.$fileName):'/assets/img/icon-play.png'
        );
        exit(json_encode($data));
    }

    public function filetxtAction() {

        $file_dir = '/www/wwwroot/wxc/wxch5/dist/Images/admin/file/'.date('Ymd');
        $url = "http://wxch5.chei.org/Images/admin/file/".date('Ymd');
        $targetDir = APP_ROOT.'/upload_tmp';
        $uploadDir = $file_dir;

        $cleanupTargetDir = true;
        $maxFileAge = 5 * 3600;
        if (!file_exists($targetDir)) {
            File::makeDir($targetDir);
        }

        if (!file_exists($uploadDir)) {
            File::makeDir($uploadDir);
        }

        if (isset($_REQUEST["name"])) {
            $fileExt = strtolower(substr(strrchr($_REQUEST["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif(in_array($fileExt, array('php'))) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_REQUEST["name"]).'.'.$fileExt;
            }


        } elseif (!empty($_FILES)) {
            $fileExt = strtolower(substr(strrchr($_FILES["file"]["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif (strpos($_FILES["file"]['type'], 'php')) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_FILES["file"]["name"]).'.'.$fileExt;
            }
        } else {
            $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }

//        //oss上传
//
//        $ossClient = new OssClient(Configure::get('oss.access_key'), Configure::get('oss.access_secret'), Configure::get('oss.endpoint'), false);
//        try {
//            $ossClient->multiuploadFile(Configure::get('oss.bucket'), $file_dir.'/'.$fileName, $uploadPath, array());
//        } catch (OssException $e) {
//            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream.'.$e->getMessage().'"}, "id" : "id"}');
//        }
        $data = array(
            'jsonrpc' => '2.0',
            'result' => null,
            'id' => 'id',
            'error' => array(
                'code' => 0
            ),
            'url' => $url.'/'.$fileName,
            'image' => in_array($fileExt, array('jpg','png','gif','jpeg'))?($url.'/'.$fileName):'/assets/img/icon-play.png'
        );
        exit(json_encode($data));
    }
    
    public function videoAction() {
        set_time_limit(0);
        ini_set('memory_limit', '512M');
        $file_dir = '/upload/'.date('Ymd');
        $url = Request::getServerName().Router::getBaseUrl().$file_dir;
        $targetDir = APP_ROOT.'/upload_tmp';
        $uploadDir = APP_ROOT.$file_dir;

        $cleanupTargetDir = true;
        $maxFileAge = 5 * 3600;
        if (!file_exists($targetDir)) {
            File::makeDir($targetDir);
        }
        
        if (!file_exists($uploadDir)) {
            File::makeDir($uploadDir);
        }
        
        if (isset($_REQUEST["name"])) {
            $fileExt = strtolower(substr(strrchr($_REQUEST["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif(in_array($fileExt, array('php'))) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_REQUEST["name"]).'.'.$fileExt;
            }
            
            
        } elseif (!empty($_FILES)) {
            $fileExt = strtolower(substr(strrchr($_FILES["file"]["name"], '.'), 1));
            if(in_array($fileExt, array('jpg','png','gif','jpeg'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }
            elseif (strpos($_FILES["file"]['type'], 'php')) {
                Response::ajax(SYSTEM_ERROR, '文件上传失败！请重新上传');
            }
            else{
                $fileName = md5($_FILES["file"]["name"]).'.'.$fileExt;
            }
        } else {
            $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096000)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        
//        //oss上传
//        
//        $ossClient = new OssClient(Configure::get('oss.access_key'), Configure::get('oss.access_secret'), Configure::get('oss.endpoint'), false);
//        try {
//            $ossClient->multiuploadFile(Configure::get('oss.bucket'), $file_dir.'/'.$fileName, $uploadPath, array());
//        } catch (OssException $e) {
//            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream.'.$e->getMessage().'"}, "id" : "id"}');
//        }
        $imageUrl = $gifUrl = '';
        $uniqName = uniqid();
        $gifFile = $uploadDir.DS.$uniqName.'.gif';
        $imageFile= $uploadDir.DS.$uniqName.'.jpg';
        
        try{
            //生成gif图片
            $output = '';
            @exec("/sbin/ffmpeg -t 3 -ss 00:00:01 -i '{$uploadPath}' '{$gifFile}'", $output);
            $gifUrl = $url .'/'. $uniqName.'.gif';
            //生成jpg图片
            @exec("/sbin/ffmpeg -i '{$uploadPath}' -y -f image2 -ss 1 -vframes 1  '{$imageFile}'", $output);
            $imageUrl = $url .'/'. $uniqName.'.jpg';
        } catch (Exception $ex) {
            $imageUrl = 'default.jpg';
            $gifUrl = 'default.gif';
            Log::write('视频转码失败:'.$ex, 'WARN');
        }
        $data = array(
            'jsonrpc' => '2.0',
            'result' => null,
            'id' => 'id',
            'error' => array(
                'code' => 0
            ),
            'gifImage' => $gifUrl,
            'url' => $url.'/'.$fileName,
            'image' => $imageUrl
        );
        exit(json_encode($data));
    }

    public function editorAction() {
        $fileName = 'imgFile';
        $fileType = Request::get('dir');
        //定义允许上传的文件扩展名
        $ext_arr = array(
                'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
                'flash' => array('swf', 'flv'),
                'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
                'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        $fileUpload = $this->instance('FileUpload');
        if(!$fileUpload->uploadFileError($_FILES[$fileName]['error'])) {
            $this->alert($fileUpload->getErrorInfo());
        }
        $fileTmp = uniqid('qx');
        $dirTmp = '/upload/' . date('Ymd', time()) . '/';
        $desDir = APP_ROOT .'/public' . $dirTmp;
        File::makeDir($desDir);
        $desFile = $desDir . $fileTmp;
        $status= $fileUpload->setLimitType($ext_arr[$fileType])->setLimitSize(20480000)->moveFile($_FILES[$fileName], $desFile);
        if(!$status){
            $this->alert($fileUpload->getErrorInfo());
        }
        $urlFile =  Request::getServerName() . $dirTmp . $fileTmp . '.' . $fileUpload->_ext;
        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(array('error' => 0, 'url' => $urlFile));
        exit;
    }
    
    public function zipAction() {
        set_time_limit(0);
        ini_set('memory_limit', '512M');
        $file_dir = 'upload/images';
        $targetDir = APP_ROOT.'/public/upload_tmp';
        $uploadDir = APP_ROOT.'/public/'.$file_dir;

        $cleanupTargetDir = true;
        $maxFileAge = 5 * 3600;
        if (!file_exists($targetDir)) {
            File::makeDir($targetDir);
        }
        if (!file_exists($uploadDir)) {
            File::makeDir($uploadDir);
        }
        
        if (isset($_REQUEST["name"])) {
            $fileExt = strtolower(substr(strrchr($_REQUEST["name"], '.'), 1));
            if(in_array($fileExt, array('zip'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }else{
                $fileName = md5($_REQUEST["name"]).'.'.$fileExt;
            }
            
        } elseif (!empty($_FILES)) {
            $fileExt = strtolower(substr(strrchr($_FILES["file"]["name"], '.'), 1));
            if(in_array($fileExt, array('zip'))) {
                $fileName = uniqid('wf_').'.'.$fileExt;
            }else{
                $fileName = md5($_FILES["file"]["name"]).'.'.$fileExt;
            }
        } else {
            $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }

        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
//        $uploadPath = APP_ROOT.'/public/test.zip';
        $zip = new ZipArchive; 
        $res = $zip->open($uploadPath);
        if ($res === TRUE) {
            $result = $zip->extractTo(APP_ROOT.'/public/upload/images');
            $zip->close();
            if($result) {
                unlink($uploadPath);
                $this->returnMsg(200, '解压成功');
            }
        }
        $this->returnMsg(NORMAL_ERROR, '解压文件失败');
        
    }
    
    
    public function returnMsg($status, $msg, $data=[]) {
        $result = array(
            'jsonrpc' => '2.0',
            'result' => [
                'status' => $status,
                'msg' => $msg,
                'data' => $data
            ],
            'id' => 'id',
            'error' => array(
                'code' => 0
            )
        );
        exit(json_encode($result));
    }
    
    
    private function alert($msg) {
        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(array('error' => 1, 'message' => $msg));
        exit;
    }
}